#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) Copyright 2010 - BidiX@BidiX.info
#
#
'''
    db - db package
'''
from google.appengine.ext import db
from google.appengine.ext import admin

from bidix.html import ustr

class Entity(db.Model):
    ''' '''
    def format_to_form(self, post_url):
#        form = """
#        <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
#<html xmlns="http://www.w3.org/1999/xhtml">
#  <head>
#    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
#    </head>
#    <body>Ò
#"""
        form = """<form method="post" action="%s">"""%post_url
        form +="""<table>"""
        form +="""<tr><td>name : </td><td><input name="name" value="%(value)s"/></td></tr>\n"""%{'value': self.key().id_or_name()}

        for (name, value) in self.properties().iteritems():
            class_name = value.__class__.__name__
            if class_name == 'StringProperty':
                form +="""<tr><td>%(name)s : </td><td><input name="%(name)s" value="%(value)s"/></td></tr>\n"""%{'name': name,'value': getattr(self, name)}
            elif class_name == 'TextProperty':
                form +="""<tr><td>%(name)s : </td><td><textarea id ="tinymce" name="%(name)s" rows=10 cols=80>%(value)s</textarea></td></tr>\n"""%{'name': name,'value': getattr(self, name)}
            elif class_name == 'StringListProperty':
                value_list = ""
                for l in getattr(self, name):
                    value_list += " "+l
                value_list += ""
                form +="""<tr><td>%(name)s : </td><td><input name="%(name)s" value="%(value)s"/></td></tr>\n"""%{'name': name,'value': value_list}
            else:
                form +="""<tr><td>%(name)s : </td><td>%(value)s</td></tr>\n"""%{'name': name,'value': str(getattr(self, name))}
        form += """<tr><td colspan="2"><center><input type="submit" value="add or replace"/></center></td>"""
        form +="""</table>"""
        form +="""</form>"""
        return form

    def format_to_html(self):
        html = "<table>\n"
        for (name, value) in self.properties().iteritems():
            html += "<tr><td>%s</td><td>%s</td>\n"%(name,str(getattr(self, name)))
        html += "</table>\n"
        return html

    def format_to_txt(self):
        txt = ""
        for (name, value) in self.properties().iteritems():
            txt += name 
            txt += "(%s)"%value.__class__.__name__
            txt += ": " + str(getattr(self, name))
            txt += "\n\n"
        return txt

    def format_to_xml(self):
        return self.to_xml()
    
    @classmethod
    def add_or_replace(cls, key_name, **kwds):
        e = cls(key_name, **kwds)
        e.put()
        return e

    @classmethod
    def get_by_name(cls,name):
        return cls.get_by_key_name(name)


class Article(Entity):
    ''' '''
    #name always present
    title = db.StringProperty()
    text = db.TextProperty()
    creator = db.UserProperty(auto_current_user_add=True)
    editor = db.UserProperty(auto_current_user=True)
    created = db.DateTimeProperty(required=True, auto_now_add=True)
    modified = db.DateTimeProperty(required=True, auto_now=True)
    tags = db.StringListProperty()

    def __init__(self,
               parent=None,
               key_name=None,
               _app=None,
               _from_entity=False,
               **kwds):
      '''key_name contains the same value as name'''
      #assert name
      name = None
      if kwds.has_key('name'):
          name = kwds['name']
          db.Model.__init__(self, key_name=name, **kwds)
      else:
          db.Model.__init__(self, **kwds)
      
    def format_to_html(self):
        html = """<h1 class="article-title">%s</h1>\n"""%ustr(self.title)
        html += """<div class="article-txt">%s</div>\n"""%ustr(self.text)
        html += """<div class="article-tags">"""
        first = True
        for tag in self.tags:
            if not first:
                html += ", "
            else:
                first = False
            html += tag
        html += "</div>"
        return html

